package backend

import (
	"awesomeProject1/models"
	"awesomeProject1/pkg/db"
	"fmt"
	"github.com/simplechain-org/client/log"
	"strings"
)

func (b *backend) initDB() error {
	dbObject, err := db.New(b.conf.DB)
	if err != nil {
		return err
	}

	err = dbObject.Sync2(models.TablesCreateList...)
	if err != nil {
		log.Error(fmt.Sprintf("数据库表格同步失败, err: %s", err.Error()))
		return err
	}

	n, err := dbObject.Insert(models.DefaultValue...)
	if err != nil && !strings.Contains(err.Error(), "Duplicate entry") && !strings.Contains(err.Error(), "-6602:") {
		log.Error(fmt.Sprintf("effect rows: %d ,default value insert err: %s", n, err.Error()))
		return err
	}

	b.db = dbObject
	return nil
}

func (b *backend) initDBOnline() error {
	dbOnlineList, err := db.NewOnlineList(b.conf.DBOnlineList, b.conf.DB)
	if err != nil {
		return err
	}
	b.dbOnlineList = dbOnlineList
	return nil
}
